package com.qing.common_result.result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理
 */
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {


	@ExceptionHandler(value = Exception.class) // 捕获 Controller 中抛出的指定类型的异常，也可以指定其他异常
	public Object handler(Exception exception, HttpServletRequest request) {
//         log.info("进入异常 处理中 ----------------------------------------");
		//去掉统一拦截打的标签，避免进入统一处理返回值方法
		request.removeAttribute(CommonFinal.RESPONSE_RESULT_ANN);
		exception.printStackTrace();
		//记录异常信息
		if (exception instanceof CommonException) {  //自定义异常
			CommonException customException = (CommonException) exception;
			return Result.failure(customException.getCommonEnum().getCode(), customException.getCommonEnum().getMessage(), exception.getMessage());
		} else if (exception instanceof NoHandlerFoundException) { //404异常处理
			return Result.failure(ResultCode.PAGE_NOT_FOUND);
		} else {  //500异常
			return Result.failure(ResultCode.UNKNOWN_EXCEPTION);
		}

	}


}
